<template>
  <page-layout v-if="!isLoading">
    <a-row :gutter="[10, 10]">
      <a-col :span="24">
        <a-card>
          <!-- 查询参数 -->
          <pro-query
            :searchParam="searchParams.params"
            :labelCol="{ span: 10 }"
            :wrapperCol="{ span: 14 }"
            @on-search="search"
            @on-reset="reset"
          />
          <!-- 列表 -->
          <pro-table
            ref="tableRef"
            :pagination="pagination"
            :fetch="fetch"
            :columns="tableConfig.columns"
            :operate="tableConfig.operate"
            :param="state.param"
            :toolbar="toolbar"
            :row-selection="{
              selectedRowKeys: state.selectedRowKeys,
              onChange: onSelectChange,
            }"
          />
        </a-card>
      </a-col>
    </a-row>
    <importModal
      :exportConfig="exportConfig"
      :visible="state.importVisible"
      @close="closeImport"
    ></importModal>
  </page-layout>
  <a-modal
    v-model:visible="state.showVisible"
    title="批量修改负责人"
    :cancelText="t('button.cancel')"
    :okText="t('button.save')"
    width="60%"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form :model="state.modalData">
      <a-row>
        <a-col :span="8">
          <a-form-item :label="t('school-manage.label.head')">
            <a-input
              v-model:value="state.modalData.schResponsiblePersonName"
              placeholder="请选择"
              readonly="readonly"
              @click="openModal"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
  <BasicTableModal
    v-if="modalConfig.show"
    v-model:visible="modalConfig.show"
    :columns="modalConfig.columns"
    :fetchAjax="userPage"
    title="负责人"
    :isinput="true"
    @selectUniversity="selectPerson"
  />
</template>
<script>
export default {
  name: 'college-manage',
}
</script>
<script setup>
import { message, Modal } from "ant-design-vue";
import {
  page,
  remove,
  templateUrl,
  imports,
  removeBatch,
  updateUser
} from "@/api/module/school";
import { page as userPage } from "@/api/module/user";
import { ref, defineComponent, reactive, onMounted, watch, onActivated } from "vue";
import { useRouter, useRoute } from "vue-router";
import { btnIsPowerByCode, filterEmptyByObject } from "@/tools/common";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import dictEnum from "@/const/dict";
import importModal from "@/component/import/index.vue";
import BasicTableModal from "@/component/basic-table-modal";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

const router = useRouter();
const route = useRoute();
const handleChange = (value) => {
  console.log(`selected ${value}`);
};
const toolbar = [
  {
    code: "college-manage:add",
    label: "新增",
    type: "primary",
    event: () => {
      goNewSchool();
    },
  },
  {
    code: "college-manage:batch-user",
    label: "修改负责人",
    type: "primary",
    event: () => {
      if (state.selectedRowKeys && !state.selectedRowKeys.length) {
        return message.error("请先选择数据");
      }
      state.showVisible = true
    },
  },
  {
    code: "college-manage:batch-remove",
    label: "批量删除",
    type: "danger",
    event: () => {
      if (state.selectedRowKeys && !state.selectedRowKeys.length) {
        return message.error("请先选择数据");
      }
      Modal.confirm({
        title: "你需要批量删除该学校数据吗？",
        okText: "是",
        okType: "danger",
        cancelText: "否",
        onOk() {
          removeBatch({ ids: [...state.selectedRowKeys] }).then((response) => {
            if (response.success) {
              message.success({ content: "删除成功" });
              tableRef.value.reload();
            } else {
              message.error({ content: "删除失败" });
            }
          });
        },
      });
    },
  },
  {
    code: "college-manage:batch-import",
    label: "批量导入",
    type: "",
    event: () => {
      handleExport();
    },
  },
];
const tableRef = ref(null);
const exportConfig = reactive({
  title: "学校管理",
  exportExcel: imports,
  templateUrl: templateUrl,
  downMethod: "GET",
  fileName: "学校管理导入模板",
  params: {},
  suffix: 'xls'
});
const handleExport = () => {
  state.importVisible = true;
};
const closeImport = (value) => {
  state[value] = false;
  tableRef.value.reload();
};
const openModal = () => {
  modalConfig.show = true;
};
const submit = () => {
  if (!state.modalData.schResponsiblePerson) {
    return message.error("请先选择负责人");
  }
  updateUser({ schIds: [...state.selectedRowKeys], ...state.modalData }).then((response) => {
    if (response.success) {
      message.success({ content: "修改成功" });
      cancel()
      state.selectedRowKeys = []
      state.modalData = {
        schResponsiblePerson: '',
        schResponsiblePersonName: ''
      }
      tableRef.value.reload();
    } else {
      message.error({ content: "修改失败" });
    }
  });
}
const cancel = () => {
  state.showVisible = false
}
const labelCol = { span: 6 };
const wrapperCol = { span: 18 };
const pagination = {
  pageNum: 1,
  pageSize: 10,
};
const modalConfig = reactive({
  show: false,
  columns: [
    { dataIndex: "nickname", key: "nickname", title: "用户名称" },
    { dataIndex: "deptName", key: "deptName", title: "所属部门" },
    { dataIndex: "postName", key: "postName", title: "职位" }
  ]
});
const tableConfig = reactive({
  columns: [],
  operate: [
    {
      label: "详情",
      event: (item) =>
        router.push({
          path: "/university/college-manage/detail",
          query: { id: item.id },
        }),
    },
    {
      code: 'college-manage:remove',
      label: "删除",
      event: (item) => {
        Modal.confirm({
          title: "你需要删除该学校数据吗？",
          okText: "是",
          okType: "danger",
          cancelText: "否",
          onOk() {
            remove({ id: item.id }).then((response) => {
              if (response.success) {
                message.success({ content: "删除成功" });
                tableRef.value.reload();
              } else {
                message.error({ content: "删除失败" });
              }
            });
          },
        });
      },
    },
  ],
});

const isLoading = ref(false);

const state = reactive({
  selectedRowKeys: [],
  param: {},
  visibleSave: false,
  visibleEdit: false,
  visibleInfo: false,
  importVisible: false,
  showVisible: false,
  recordEdit: {},
  recordInfo: {},
  modalData: {
    schResponsiblePerson: '',
    schResponsiblePersonName: ''
  }
});

const goNewSchool = () => router.push("/university/college-manage/add");
const onSelectChange = (selectedRowKeys) => {
  state.selectedRowKeys = selectedRowKeys;
};
const fetch = async (param) => {
  console.log('param: ', param);
  const response = await page(param);
  return {
    data: response.data.record,
    total: response.data.total,
  };
};
const value = ref("");
let dictLists = reactive({
  data: {},
});
let searchParams = reactive({
  params: [],
});
let optionsA = reactive([]);
const selectPerson = record => {
  state.modalData.schResponsiblePersonName = record.nickname;
  state.modalData.schResponsiblePerson = record.id;
};
const search = (value) => {
  console.log(value);
  state.param = {
    ...state.param,
    ...filterEmptyByObject(value),
  };
};
const reset = () => {
  state.param = {};
};
watch(route, () => {
  tableRef.value.reload();
});
onActivated(() => {
  console.log('onActivated: schoole');
})
onMounted(async () => {
  console.log('onMounted: shcool  index');
  isLoading.value = true;

  dictLists.data = await getDictByCodesReturnObj([
    dictEnum.YES_OR_NO,
    dictEnum.SHC_QUALIFICATION,
    dictEnum.SCH_TYPE,
    dictEnum.SCH_SYSTEM,
    dictEnum.SCH_NATURE,
    dictEnum.FOLLOW_PROGRESS,
    dictEnum.Intention_PROJECT,
    dictEnum.STAR_XJ,
    dictEnum.WKQK,
  ]);
  console.log(dictLists.data);
  optionsA = dictLists.data[dictEnum.YES_OR_NO];
  // console.log(optionsA);
  searchParams.params = [
    {
      key: "schResponsiblePerson",
      type: "input",
      label: "负责人",
      placeholder: "请输入负责人",
    },
    {
      key: "schFollowUpProgress",
      type: "select",
      label: "跟进进度",
      placeholder: "请选择",
      options: dictLists.data[dictEnum.FOLLOW_PROGRESS],
      // hidden: true
    },
    {
      key: "schoolEnName",
      type: "input",
      label: "学校名",
      placeholder: "请输入学校名",
    },
    {
      key: "schCategory",
      type: "select",
      label: "类别",
      placeholder: "请选择",
      options: dictLists.data[dictEnum.SCH_TYPE],
      hidden: true,
    },
    {
      key: "schSchoolSystem",
      type: "select",
      label: "学制",
      placeholder: "请选择",
      options: dictLists.data[dictEnum.SCH_SYSTEM],
      hidden: true,
    },
    {
      key: "schOnlineYesno",
      type: "selectMore",
      label: "网课情况",
      placeholder: "请选择",
      mode: "multiple",
      options: dictLists.data[dictEnum.WKQK],
      hidden: true,
    },
    {
      key: "schCompetitorYesno",
      type: "select",
      label: "是否与竞争对手合作",
      placeholder: "请选择",
      options: dictLists.data[dictEnum.YES_OR_NO],
      hidden: true,
    },
    {
      key: "schstar",
      type: "select",
      label: "星级",
      placeholder: "请选择",
      options: dictLists.data[dictEnum.STAR_XJ],
      hidden: true,
    },
    {
      key: "schNature",
      type: "select",
      label: "性质",
      placeholder: "请选择",
      options: dictLists.data[dictEnum.SCH_NATURE],
      hidden: true,
    },
    {
      key: "schCountry",
      hidden: true,
      type: "input",
      label: "所属国家",
      placeholder: "所属国家",
    },
    {
      key: "schProvince",
      type: "input",
      label: "省/州",
      placeholder: "省/州",
      hidden: true,
    },
    {
      key: "qualification",
      type: "select",
      label: "学校资质",
      placeholder: "请选择",
      options: dictLists.data[dictEnum.SHC_QUALIFICATION],
      hidden: true,
    },
  ];

  tableConfig.columns = [
    {
      dataIndex: "code",
      key: "code",
      title: "学校编码",
      width: 150,
      fixed: "left",
    },
    {
      dataIndex: "schoolEnName",
      key: "schoolEnName",
      title: "学校名称",
      width: 150,
      fixed: "left",
    },
    {
      dataIndex: "schCategory",
      key: "schCategory",
      title: "类别",
      width: 150,
      cellRender: (record, data) => {
        if (dictLists.data[dictEnum.SCH_TYPE]) {
          const item = dictLists.data[dictEnum.SCH_TYPE].find(
              (v) => v.value == data
          );
          return item ? item.label : "";
        }
        return "";
      },
    },
    {
      dataIndex: "schCountry",
      key: "schCountry",
      title: "所属国家",
      width: 150,
    },
    {
      dataIndex: "schProvince",
      key: "schProvince",
      title: "省/州",
      width: 150,
    },
    {
      dataIndex: "schFollowUpProgress",
      key: "schFollowUpProgress",
      title: "跟进进度",
      width: 150,
      cellRender: (record, data) => {
        if (dictLists.data[dictEnum.FOLLOW_PROGRESS]) {
          const item = dictLists.data[dictEnum.FOLLOW_PROGRESS].find(
              (v) => v.value == data
          );
          return item ? item.label : "";
        }
        return "";
      },
    },
    {
      dataIndex: "schStar",
      key: "schStar",
      title: "星级",
      width: 150,
      cellRender: (record, data) => {
        if (dictLists.data[dictEnum.STAR_XJ]) {
          const item = dictLists.data[dictEnum.STAR_XJ].find(
              (v) => v.value == data
          );
          return item ? item.label : "";
        }
        return "";
      },
    },
    {
      dataIndex: "schResponsiblePersonName",
      key: "schResponsiblePersonName",
      title: "负责人",
      width: 150,
    },
  ];

  isLoading.value = false;
});
</script>
